<template>
  <!-- 计划回款--应收账款 -->
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
          type="primary"
          @click="returnMoney"
          v-auth-button="['returnMoney/plancollect']"
          :disabled="selection.length == 0"
          >收款</el-button
        >
        <el-button
          type="primary"
          @click="createBill"
          v-auth-button="['createBill/plancollect']"
          >生成对账单</el-button
        >
      </div>
      <div class="right-panel">
        <div class="right-panel-search">
          <!-- <el-input
            v-model="searchValue.search"
            placeholder="合同名称"
            clearable
          ></el-input> -->
          <!-- <el-input
            v-model="searchValue.cusName"
            placeholder="客户名称"
            clearable
          ></el-input> -->
          <!-- <el-select
            v-model="searchValue.customerId"
            placeholder="请选择客户"
            style="width: 100%"
            remote
            filterable
            remote-show-suffix
            :remote-method="queryCustomer"
            :loading="selectCustomerLoading"
            clearable
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            />
          </el-select> -->
          <!-- <el-select
            v-model="searchValue.planStatus"
            placeholder="请选择平账状态"
            style="width: 100%"
            clearable
          >
            <el-option label="已平账" :value="0" />
            <el-option label="未平账" :value="1" />
          </el-select> -->
          <sc-table-select
            style="width: 100%"
            v-model="searchSelect.customer"
            :apiObj="apiObjCustomer"
            :table-width="700"
            clearable
            collapse-tags
            collapse-tags-tooltip
            :props="props"
            :params="customerForm"
            @change="changeCustomer"
          >
            <template #header="{ form, submit }">
              <el-form :model="customerForm">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input
                      v-model="customerForm.name"
                      placeholder="客户名称"
                      clearable
                      style="width: 100%"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerForm.startTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="开始时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerForm.endTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="结束时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item width="100%">
                      <el-button type="primary" @click="submit">查询</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <!-- <el-alert title="自定义FORM插糟 传递了form对象和提交方法" type="info" /> -->
            </template>
            <el-table-column
              prop="customerName"
              label="客户名称"
              min-width="150"
            ></el-table-column>
            <el-table-column
              prop="numbers"
              label="合同成交量"
              min-width="150"
            ></el-table-column>
          </sc-table-select>
          <el-select
            v-model="searchValue.planStatus"
            placeholder="请选择回款状态"
            style="width: 100%"
            clearable
          >
            <el-option label="未完成" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
          <el-date-picker
            v-model="searchValue.startTime"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          >
          </el-date-picker>
          <el-date-picker
            v-model="searchValue.endTime"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          >
          </el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="upsearch"
          ></el-button>
        </div>
      </div>
    </el-header>
    <div class="count" v-auths="['financeCount']">
      <p>
        未结金额：{{
          (countMoney.totalPlanMoeny - countMoney.totalPaymentMoney).toFixed(2)
        }}元
      </p>
      <p>
        应收总额：{{
          countMoney.totalPlanMoeny == null ? 0 : countMoney.totalPlanMoeny
        }}元
      </p>
      <p>
        应收年总额：{{
          countMoney.yearPlanMoney == null ? 0 : countMoney.yearPlanMoney
        }}元
      </p>
      <p>
        应收月总额：{{
          countMoney.monthPlanMoney == null ? 0 : countMoney.monthPlanMoney
        }}元
      </p>
      <p>
        收款总额：{{
          countMoney.totalPaymentMoney == null
            ? 0
            : countMoney.totalPaymentMoney
        }}元
      </p>
      <p>
        收款年总额：{{
          countMoney.yearPaymentMoney == null ? 0 : countMoney.yearPaymentMoney
        }}元
      </p>
      <p>
        本月实收：{{
          countMoney.monthPaymentMoney == null
            ? 0
            : countMoney.monthPaymentMoney
        }}元
      </p>
    </div>
    <el-main class="nopadding">
      <scTable
        ref="table"
        :apiObj="apiObj"
        row-key="id"
        :params="searchValue"
        stripe
        @filterType="filterType"
        @row-dblclick="handleRowDblclick"
        @selection-change="handleSelection"
        :row-style="rowStyle"
        :showSummary="true"
        :summary-method="getSummaries"
      >
        <!-- <el-table-column label="ID" prop="id" width="150"></el-table-column> -->
        <!-- <el-table-column label="客户名称" prop="tomerName" min-width="200"></el-table-column> -->
        <el-table-column
          type="selection"
          width="55"
          :selectable="checkSelectable"
        >
        </el-table-column>
        <el-table-column
          label="合同编码"
          prop="contractCode"
          min-width="100"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="客户名称"
          prop="customerName"
          min-width="100"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="应收金额" prop="planMoney" width="150">
          <template #default="scope">
            <p v-if="scope.row.refundMoney == 0">{{ scope.row.planMoney }}元</p>
            <p v-if="scope.row.refundMoney != 0">
              {{ scope.row.planMoney - scope.row.refundMoney }}元(已退款{{
                scope.row.refundMoney
              }}元)
            </p>
          </template>
        </el-table-column>
        <el-table-column label="实收金额" prop="actualPlanMoney" width="100">
          <template #default="scope">
            <p>
              {{ scope.row.actualPlanMoney ? scope.row.actualPlanMoney : 0 }}元
            </p>
          </template>
        </el-table-column>
        <!-- <el-table-column label="应收款类型" prop="planPayType" width="100">
          <template #default="scope">
            <p v-if="scope.row.planPayType == 0">普通收款</p>
            <p v-if="scope.row.planPayType == 1">预付款</p>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="未结金额" prop="actualPlanMoney" width="200">
          <template #default="scope">
            <p>
              {{
                scope.row.planMoney -
                scope.row.actualPlanMoney -
                scope.row.balancingMoney
              }}元
            </p>
          </template>
        </el-table-column>
        <el-table-column label="抹零金额" prop="balancingMoney" width="200">
          <template #default="scope">
            <p>{{ scope.row.balancingMoney }}元</p>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="结算方式" prop="settlementType" width="150">
          <template #default="scope">
            <p v-if="scope.row.settlementType == 1">现结</p>
            <p v-if="scope.row.settlementType == 2">月结</p>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="平账状态" prop="planStatus" width="200">
          <template #default="scope">
            <p v-if="scope.row.planStatus == 1" style="color: #67c23a">
              已平账
            </p>
            <p v-if="scope.row.planStatus == 0" style="color: #f56c6c">
              未平账
            </p>
          </template>
        </el-table-column> -->
        <el-table-column label="收款截止日期" prop="planTime" width="120">
          <template #default="scope">
            <p>{{ scope.row.planTime }}</p>
          </template>
        </el-table-column>
        <el-table-column label="生产状态" prop="type" width="100">
          <template #default="scope">
            <p v-if="scope.row.planPayType == 1">预付款</p>
            <p v-else-if="scope.row.type == 0" style="color: #f56c6c">未生产</p>
            <p v-else-if="scope.row.type == 1" style="color: green">生产中</p>
            <p v-else-if="scope.row.type == 2" style="color: #2bd814">已完成</p>
          </template>
        </el-table-column>
        <el-table-column label="发货状态" prop="deliverStatus" width="150">
          <template #default="scope">
            <p v-if="scope.row.planPayType == 1">预付款</p>
            <p v-else-if="scope.row.deliverStatus == 0">待发货</p>
            <p v-else-if="scope.row.deliverStatus == 1" style="color: green">
              已发货
            </p>
            <p v-else-if="scope.row.deliverStatus == 2" style="color: #2bd814">
              发货完成
            </p>
          </template>
        </el-table-column>
        <!-- <el-table-column label="账单状态" prop="billStatus" width="200">
          <template #default="scope">
            <p v-if="scope.row.billStatus == 0">未生成</p>
            <p v-if="scope.row.billStatus == 1" style="color: #67c23a">
              已生成
            </p>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="状态" prop="" width="150">
          <template #default="scope">
            <p
              v-if="
                scope.row.planStatus === 0 &&
                new Date().getTime() <
                  new Date(scope.row.planTime).getTime() - 48 * 60 * 60 * 1000 &&
                scope.row.settlementType == 1
              "
              style="color: #67c23a"
            >
              回款中
            </p>
            <p
              v-if="scope.row.planStatus === 1 && scope.row.settlementType == 1"
              style="color: #398ee5"
            >
              已完成
            </p>
            <p
              v-if="
                scope.row.planStatus === 0 &&
                new Date().getTime() >
                  new Date(scope.row.planTime).getTime() - 48 * 60 * 60 * 1000 &&
                scope.row.settlementType == 1
              "
              style="color: #fd0000"
            >
             已超时(小于三天)
            </p>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="回款期数" prop="num" width="200">
        </el-table-column> -->
        <!-- <el-table-column label="备注" prop="remark" min-width="200">
        </el-table-column> -->
        <el-table-column label="操作" fixed="right" align="center" width="250">
          <template #default="scope">
            <el-button-group>
              <!-- <el-button
                text
                type="primary"
                v-if="scope.row.planStatus == 0 || scope.row.planStatus == 1"
                size="small"
                @click="returnMoney(scope.row, scope.$index)"
                v-auth-button="['show/plancollect']"
                >单笔收款</el-button
              > -->

              <el-button
                text
                type="primary"
                size="small"
                @click="table_showAll(scope.row, scope.$index)"
                v-auth-button="['show/plancollect']"
                >查看</el-button
              >
              <el-button
                text
                type="primary"
                size="small"
                @click="table_join(scope.row, scope.$index)"
                v-auth-button="['createBill/plancollect']"
                >加入对账单</el-button
              >
              <el-button
                text
                type="primary"
                size="small"
                @click="table_returnList(scope.row, scope.$index)"
                v-auth-button="['show/plancollect']"
                >收款明细</el-button
              >
              <!-- <el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)"
                v-auth-button="['edit/plancollect']">编辑</el-button> -->
              <!-- <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                <template #reference>
                  <el-button text type="primary" size="small" v-auth-button="['delete/plancollect']">删除</el-button>
                </template>
              </el-popconfirm> -->
            </el-button-group>
          </template>
        </el-table-column>
      </scTable>
    </el-main>
  </el-container>

  <join-bill-dialog
    v-if="dialog.joinBill"
    ref="joinBillDialog"
    @success="handleSaveSuccess"
    @closed="dialog.joinBill = false"
  ></join-bill-dialog>

  <create-bill-dialog
    v-if="dialog.createBill"
    ref="createBillDialog"
    @success="handleSaveSuccess"
    @closed="dialog.createBill = false"
  ></create-bill-dialog>
  <return-money-dialog
    v-if="dialog.returnMoney"
    ref="returnMoney"
    @success="handleSaveSuccess"
    @closed="dialog.returnMoney = false"
  ></return-money-dialog>
  <return-list-dialog ref="returnList"></return-list-dialog>
</template>

<script>
import joinBillDialog from "./components/joinBill"
import createBillDialog from "./components/createBill"
import returnMoneyDialog from "./components/returnMoney"
import returnListDialog from "../components/returnList"
import { queryTypeByDic } from "@/utils/getData"
export default {
  name: "plancollect",
  components: {
    joinBillDialog,
    createBillDialog,
    returnMoneyDialog,
    returnListDialog,
  },
  data () {
    return {
      dialog: {
        joinBill: false,
        createBill: false,
        returnMoney: false,
      },
      apiObj: this.$API.finance.plancollect.getPlancollectList,
      apiObjCustomer: this.$API.finance.plancollect.getCustomerNumbers,
      searchValue: {
        search: null,
        customerName: null,
        planStatus: null,
        startTime: null,
        endTime: null,
        customerId: null,
      },
      searchSelect: {},
      customerForm: {
        name: null,
        startTime: null,
        endTime: null,
      },
      props: {
        label: "customerName",
        value: "id",
      },
      columnsFilters: ['planMoney', 'actualPlanMoney'],
      selection: [],
      isSaveing: false,
      selectCustomerLoading: false,
      customerList: [],
      countMoney: []
    }
  },
  mounted () {
    //this.getCustomerList()
    this.getCountMoney()
  },
  methods: {
    //添加
    add () {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open()
      })
    },
    async getCountMoney () {
      var res = await this.$API.finance.plancollect.getCountMoney.get()
      this.countMoney = res.data
    },
    //合计行统计
    getSummaries (param) {
      console.log(param)
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "页合计"
          return
        }
        if (this.columnsFilters.includes(column.property)) {
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += " 元"
          } else {
            sums[index] = ""
          }
        }
      })
      return sums
    },
    //值变化
    changeCustomer (val) {
      this.searchValue.customerId = val.id
    },
    //编辑
    table_edit (row) {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open("edit").setData(row)
      })
    },
    //收款
    returnMoney () {
      this.dialog.returnMoney = true
      this.$nextTick(() => {
        this.$refs.returnMoney.open(this.selection)
      })
    },
    // 加入对账单
    table_join (row) {
      this.dialog.joinBill = true
      this.$nextTick(() => {
        this.$refs.joinBillDialog.open(row)
      })
    },
    // 生成对账单
    async createBill () {
      if (!this.searchValue.customerId) {
        this.$message.error("请选择客户")
        return
      }
      if (!this.searchValue.startTime) {
        this.$message.error("请选择开始时间")
        return
      }
      if (!this.searchValue.endTime) {
        this.$message.error("请选择结束时间")
        return
      }

      let data = {
        customerId: this.searchValue.customerId,
        startTime: this.searchValue.startTime,
        endTime: this.searchValue.endTime,
      }
      this.isSaveing = true
      let res = await this.$API.finance.bill.addBill.post(data)
      this.isSaveing = false
      if (res.code == 200) {
        this.$emit("success")
        this.visible = false
        this.$message.success("操作成功")
      }
    },
    //查看
    table_show (row) {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open("show").setData(row)
      })
    },
    // 收款明细
    table_returnList (row) {
      let api = this.$API.finance.plancollect.returnList
      this.$refs.returnList.open(row, api, 1)
    },
    // 查看合同总详情
    table_showAll (row) {
      this.$router.push({
        path: "/contract/contractManagement/detailList",
        query: {
          id: row.contractId,
        },
      })
    },
    //删除
    async table_del (row) {
      let data = {
        id: row.id,
        projectId: row.projectId,
      }
      var res = await this.$API.finance.plancollect.deletePlancollect.post(data)
      if (res.code == 200) {
        this.$refs.table.refresh()
        this.$message.success("删除成功")
      }
    },

    // 选择
    handleSelection (list) {
      this.selection = list
    },

    // 判断是否可被选择
    checkSelectable (row) {
      return row.planStatus == 0
    },

    // 获取客户列表
    async getCustomerList (val) {
      this.selectCustomerLoading = true
      let param = {
        limit: 1000,
        page: 1,
        search: val,
        //settlement: 2//结算方式 1现结 2月结
      }
      let res = await this.$API.customer.getCustomers.get(param)
      this.selectCustomerLoading = false
      this.customerList = res.data
    },
    // 搜索客户
    queryCustomer (val) {
      this.getCustomerList(val)
    },

    //搜索
    upsearch () {
      this.$refs.table.upData(this.searchValue)
    },

    //本地更新数据
    handleSaveSuccess () {
      this.$refs.table.refresh()
    },
    // 处理回款方式
    filterType (data) {
      let tableData = data
      queryTypeByDic("payment").then((res) => {
        let list = res
        tableData.forEach((item) => {
          list.forEach((f_item) => {
            if (item.planType == f_item.value) {
              item.planTypeName = f_item.name
            }
          })
        })
      })
    },
    // 双击表格
    handleRowDblclick (row) {
      this.table_showAll(row)
    },
    rowStyle ({ row }) {
      if (
        row.planStatus === 0 &&
        new Date().getTime() > new Date(row.planTime).getTime() - 48 * 60 * 60 * 1000 &&
        row.settlementType == 1
      ) {
        // return { 'background-color': '#ff8a8a' }
        return { color: "#fd0000" }
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.count {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 50px;
  padding-left: 12px;
  font-size: 14px;
  color: #555;
  font-weight: 600;
  p {
    margin-right: 20px;
  }
}
</style>